package com.xy.p2p.action.admin;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xy.common.page.Pagination;
import com.xy.common.web.CookieUtils;
import com.xy.core.web.WebErrors;
import com.xy.p2p.model.Trole;
import com.xy.p2p.model.Trolepermission;
import com.xy.p2p.service.TroleService;
import com.xy.p2p.service.TrolepermissionService;



@Controller
public class TroleAction{
	private static final Logger log = LoggerFactory.getLogger(TroleAction.class);
	public TroleAction() {
	}
 
 
 	/**
	 * 角色新增页面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_troleAdd.do")
	public String add(HttpServletRequest request, ModelMap model) {
		model.addAttribute("trole", new Trole());
		setDict(model);
		model.addAttribute("perms", new ArrayList<String>());
		return "troleEdit";
	}

	/**
	 * 角色新增保存
	 * 
	 * @param trole
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/o_troleSave.do")
	public String save(Trole trole, HttpServletRequest request, ModelMap model,
			String[] perms) {
		WebErrors errors = validateSave(trole, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}

		if (trole.getTusers() == null || trole.getTusers().size() == 0) {
			trole.setTusers(null);
		}
		if (trole.getTrolepermissions() == null
				|| trole.getTrolepermissions().size() == 0) {
			trole.setTrolepermissions(null);
		}

		trole = troleService.save(trole);
		if (perms != null) {
			//
			Set<Trolepermission> rpset = trole.getTrolepermissions();
			if (rpset != null) {
				for (Trolepermission t : rpset)
					trolepermissionService.remove(t.getPermid());
			}
			Set<String> set = splitPerms(perms);
			for (String p : set) {
				Trolepermission tp = new Trolepermission(trole, p);
				trolepermissionService.save(tp);

			}

		}

		return "redirect:v_troleList.do";
	}
	private Set<String> splitPerms(String[] perms) {
		Set<String> set = new HashSet<String>();
		if (perms != null) {
			for (String perm : perms) {
				for (String p : StringUtils.split(perm, ',')) {
					if (!StringUtils.isBlank(p)) {
						set.add(p);
					}
				}
			}
		}
		return set;
	}
	/**
	 * 角色删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("o_troleDelete.do")
	public String delete(long[] ids) {
		if (ids != null) {
			for (long id : ids) {
				Trole t = troleService.get(id);
				Set<Trolepermission> set = t.getTrolepermissions();
				for (Trolepermission tr : set) {
					trolepermissionService.remove(tr.getPermid());
				}
				troleService.remove(id);
			}
		}
		return "redirect:v_troleList.do";
	}

	/**
	 * 角色编辑页面
	 * 
	 * @param roleid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_troleEdit.do")
	public String edit(long roleid, HttpServletRequest request, ModelMap model) {
		Trole trole = troleService.get(roleid);
		model.addAttribute("trole", trole);
		Set<Trolepermission> set = trole.getTrolepermissions();
		List<String> l = new ArrayList<String>();
		for (Trolepermission t : set) {
			l.add(t.getUri());
		}
		model.addAttribute("perms", l);
		setDict(model);
		return "troleEdit";
	}

	/**
	 * 角色详情
	 * 
	 * @param roleid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_troleDetail.do")
	public String detail(long roleid, HttpServletRequest request, ModelMap model) {
		Trole trole = troleService.get(roleid);
		model.addAttribute("trole", trole);
        setDict(model);
		return "troleView";
	}

	/**
	 * 角色查询（分页）
	 * 
	 * @param trole
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_troleList.do")
	public String listPage(Trole trole, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		if (pageNo == null)
			pageNo = 1;
		Pagination pagination = troleService.getTroleByPage(toMap(trole),
				pageNo, CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
        setDict(model);
		return "troleList";
	}

	/**
	 * 角色查询
	 * 
	 * @param trole
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_troleList1.do")
	public String list(Trole trole, HttpServletRequest request, ModelMap model) {
		List<Trole> list = troleService.getTrole(toMap(trole));
		model.addAttribute("list", list);
        setDict(model);
		return "troleList";
	}


 	/***
	 * 将页面输入信息转成map
	 * 
	 * @param trole
	 * @return
	 */	private Map<String,Object> toMap(Trole trole){
		Map<String,Object> map=new HashMap<String, Object>();
      		if(trole.getRoleid()!=null&&!trole.getRoleid().equals("")){
			map.put("roleid", trole.getRoleid());
		}
		if(trole.getRolename()!=null&&!trole.getRolename().equals("")){
			map.put("rolename", trole.getRolename());
		}
	    
		return map;
	}
   
	/**
	 * 设置页面所需的数据字典
	 * @param model
	 */
	private void setDict(ModelMap model){
		
	}

	/**
	 * 数据校验
	 * @param model
	 */
	private WebErrors validateSave(Trole trole, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		/**if (errors.ifOutOfLength(username, "username", 1, 100)) {
			return errors;
		}  */    
		return errors;
	}

   

	@Resource
	private TrolepermissionService trolepermissionService;
	@Resource
	private TroleService troleService;   
}